05. Python and C++ Comparison

Python and C++ Comparison

Goal of this Module

The main goal of this module is to prepare you for writing C++ code. Because you are already familiar with coding practices in Python, the module will emphasize the similarities and differences between the two languages.

These lessons assume you are already familiar with general programming ideas like writing for loops, while loops, assigning values to variables, and writing functions. The fundamentals of how to code remain the same.

Learning a New Programming Language

The best way to learn a new programming language is to practice writing code; therefore, most of this lesson involves learning C++ syntax and then practicing the syntax in an exercise.

By the end of the lesson, you should feel confident translating Python code into C++ code.

Throughout this lesson, you will be presented with Python code and the C++ equivalent. Below is an example of a simple program in Python alongside a C++ version. Both versions do exactly the same thing; they assign an integer 5 to the variable x. Then they output the value of x to the terminal.

Study each example line by line. Notice the similarities as well as the differences:

One similarity is variable assignment: x = 5. And the overall structure of the programs are the same.

But there are also a few major differences:

  • the C++ program is wrapped with a function called main()
  • x has to be explicitly defined as an integer
  • instead of using print() to output the results to terminal, the code uses std::cout

You are going to learn about all of these facets (and more) in this C++ lesson.

Include

What do you think the code line #include <iostream> is for?

SOLUTION:
  • The include statement pastes the iostream file into the program when the program is compiled.
  • That code line gives the program access to the library where `std::cout` is defined.

The semi-colon

In the C++ code above, every command ended with a semi-colon. What is Python's equivalent of the semi-colon?

SOLUTION: Hitting return (ie enter) after each line of Python code

Curly Braces

What do you think the curly braces are used for in C++, and what might the equivalent be in Python?

SOLUTION: Curly braces group a set of statements together. The Python equivalent is indentation.